<template>
  <scroll
    class="listview"
    :data="singerData"
    ref="listview"
    :listenScroll="listenScroll"
    :probeType="probeType"
    @scroll="scroll"
  >
    <ul>
      <li v-for="(group, index) of singerData" :key="index" class="list-group" ref="listGroup">
        <h2 class="list-group-title">{{ group.title }}</h2>
        <ul>
          <li v-for="(item, index) of group.items"
              :key="index"
              @click="selectItem(item)"
              class="list-group-item"
          >
            <img class="avatar" v-lazy="item.picUrl" alt />
            <span class="name">{{ item.name }}</span>
          </li>
        </ul>
      </li>
    </ul>
    <div
      class="list-shortcut"
      @touchstart="onShortcutTouchStart"
      @touchmove.stop.prevent="onShortcutTouchMove"
    >
      <ul>
        <li
          class="item"
          v-for="(item, index) in shortcutList"
          :key="item"
          :data-index="index"
          :class="{'current': currentIndex === index}"
        >{{ item }}</li>
      </ul>
    </div>
    <div class="list-fixed" v-show="fixedTitle" ref="fixed">
      <h1 class="fixed-title">{{ fixedTitle }}</h1>
    </div>
    <div class="loading-container">
      <loading />
    </div>
  </scroll>
</template>

<script>
import Scroll from '@/base/scroll/Scroll'
import Loading from '@/base/loading/Loading'
import { getData } from '@/assets/js/dom'
/*
clientY: 返回触点相对于可见视区(visual viewport)上边沿的的Y坐标.
不包括任何滚动偏移.这个值会根据用户对可见视区的缩放行为而发生变化.

pageY: 触点相对于HTML文档上边沿的的Y坐标. 和 clientY 属性不同, 这个值是相对于整个html文档的坐标, 和用户滚动位置无关.
因此当存在垂直滚动的偏移时, 这个值包含了垂直滚动的偏移
*/
const ANCHOR_HEIGHT = 18
const TITLE_HEIGHT = 30

export default {
  name: 'ListView',
  props: {
    singerData: {
      type: Array,
      default: () => [],
      required: true
    }
  },
  data () {
    return {
      scrollY: -1,
      currentIndex: 0,
      diff: -1
    }
  },
  created () {
    this.touch = {}
    this.listenScroll = true
    this.listHeight = []
    // 监听实时滚动不节流的方式 (给BScroll传的)
    this.probeType = 3
  },
  computed: {
    shortcutList () {
      return this.singerData.map(group => {
        return group.title.substring(0, 1)
      })
    },
    fixedTitle() {
      if (this.scrollY > 0) {
        return ''
      }
      return this.singerData[this.currentIndex] ? this.singerData[this.currentIndex].title : ''
    }
  },
  methods: {
    selectItem(item) {
      // 这里listview是一个技术组件, 这里不参与业务相关的代码, 将事件派发出去, 告诉外部我被点击了,以及点击我的元素是什么
      this.$emit('select', item)
    },
    onShortcutTouchStart (e) {
      // 通过dom.js操作dom的函数中的getData获取列表中index属性值
      const anchorIndex = getData(e.target, 'index')
      const firstTouch = e.touches[0]
      this.touch.y1 = firstTouch.pageY
      // 将anchorIndex保存到created周期函数中定义的touch对象上
      this.touch.anchorIndex = anchorIndex
      this._scrollTo(anchorIndex)
    },
    onShortcutTouchMove (e) {
      const firstTouch = e.touches[0]
      // 这里touches中的pageY值随鼠标拉扯就会随意变化
      this.touch.y2 = firstTouch.pageY
      // 这里的 或 0 相当于Math.floor向下取整
      const delta = (this.touch.y2 - this.touch.y1) / ANCHOR_HEIGHT | 0
      const anchorIndex = parseInt(this.touch.anchorIndex) + delta
      this._scrollTo(anchorIndex)
    },
    scroll (pos) {
      this.scrollY = pos.y
    },
    refresh() {
      this.$refs.listview.refresh()
    },
    _scrollTo (index) {
      if (!index && index !== 0) {
        // 因为字母导航上下有空隙, 不需要监听点击的, 点击的时候index = null, 所以index = null 或者index = 0就不监听
        return
      }
      /*
      因为右侧字母导航的高亮不会因为点击事件改变(只能鼠标点击移动才有效果), 因为字母高亮是因为scrollY的变化计算得来的,
      但是点击事件不会触发scroll的scroll事件, 点击是使用scrollToElement直接做移动,
      scrollToElement不会派发scrollY数据过来, 我们就得手动设置scrollY
      */
      if (index < 0) {
        index = 0
      } else if (index > this.listHeight.length - 2) {
        index = this.listHeight.length - 2
      }
      this.scrollY = -this.listHeight[index]
      // scrollToElement 的第二个参数是一个缓动动画的时间
      this.$refs.listview.scrollToElement(this.$refs.listGroup[index], 0)
    },
    _calculateHeight () {
      // 获取从第一个到最后一个每一个Group所对应距离顶部的距离的height
      this.listHeight = []
      const list = this.$refs.listGroup
      let height = 0
      this.listHeight.push(height)
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        height += item.clientHeight
        this.listHeight.push(height)
      }
    }
  },
  watch: {
    singerData () {
      setTimeout(() => {
        this._calculateHeight()
      }, 90)
    },
    scrollY (newY) {
      const listHeight = this.listHeight
      // 当滚动到顶部(并向下拉), newY>0
      if (newY > 0) {
        this.currentIndex = 0
        return
      }
      // 在中间部分滚动
      for (let i = 0; i < listHeight.length - 1; i++) {
        const height1 = listHeight[i]
        const height2 = listHeight[i + 1]
        if (-newY >= height1 && -newY < height2) {
          this.currentIndex = i
          this.diff = height2 + newY
          return
        }
      }
      // 当滚动到底部, 且-newY大于最后一个元素的上限
      this.currentIndex = listHeight.length - 2
    },
    diff(newVal) {
      const fixedTop = (newVal > 0 && newVal < TITLE_HEIGHT) ? newVal - TITLE_HEIGHT : 0
      // 因为fixedTop已经是一个实时改变的值, 而且要修改dom, 所以只有下面的标题顶到了上面的标题才需要去修改dom (性能问题)
      if (this.fixedTop === fixedTop) {
        return
      }
      this.fixedTop = fixedTop
      this.$refs.fixed.style.transform = `translate3d(0, ${fixedTop}px, 0)`
    }
  },
  components: {
    Scroll,
    Loading
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/css/variable.scss";
.listview {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: $color-background;
  .list-group {
    padding-bottom: 30px;
    .list-group-title {
      height: 30px;
      line-height: 30px;
      padding-left: 20px;
      font-size: $font-size-small;
      color: $color-text-l;
      background: $color-highlight-background;
    }
    .list-group-item {
      display: flex;
      align-items: center;
      padding: 20px 0 0 30px;
      .avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }
      .name {
        margin-left: 20px;
        color: $color-text-l;
        font-size: $font-size-medium;
      }
    }
  }
  .list-shortcut {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 20px;
    padding: 20px 0;
    border-radius: 10px;
    text-align: center;
    background: $color-background-d;
    .item {
      padding: 3px;
      line-height: 1;
      color: $color-text-l;
      font-size: $font-size-small;
      &.current {
        color: $color-theme;
      }
    }
  }
  .list-fixed{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    .fixed-title{
      height: 30px;
      line-height: 30px;
      padding-left: 20px;
      font-size: $font-size-small;
      color: $color-text-l;
      background: $color-highlight-background;
    }
  }
  .loading-container{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
  }
}
</style>